package com.baizhi.video.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baizhi.feign.client.user.UserClient;
import com.baizhi.model.entity.User;
import com.baizhi.model.entity.Video;
import com.baizhi.video.dao.VideoMapper;
import com.baizhi.video.service.IVideoService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 视频 服务实现类
 * </p>
 *
 * @author gange
 * @since 2023-07-18
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {
    @Autowired
    private UserClient userClient;
    @Override
    public Map<String, Object> selectVideo(Integer page, Integer per_page, Integer id, String name, Integer category_id, String uploader_name) {
        Map<String,Object> map = new HashMap<>();
        //1.使用openfeign根据uploader_name查询出up主的id值（1，2，3）
        Integer[] uids = null;
        if(StrUtil.isNotEmpty(uploader_name)){
            List<User> users = userClient.selectByName(uploader_name);
            if(CollectionUtil.isNotEmpty(users)){
                uids = new Integer[users.size()];
                for(int i=0;i<uids.length;i++){
                    uids[i]=users.get(i).getId();
                }
            }else{
                map.put("total_count",0);
                map.put("items", Collections.emptyList());
                return map;
            }
        }

        //2.调用dao得到视频信息。
        Page<Video> p = new Page<>(page,per_page);
        IPage<Video> ipage = baseMapper.searchVideo(p,id,name,category_id,uids);
        //3.遍历分页集合里面的每个video对象，把video里面的up主信息查询出来。远程调用。
        List<Video> records = ipage.getRecords();
        for(Video video:records){
            User user = userClient.selectById(video.getUid());
            video.setUploader(user);
        }
        //4.响应结果

        map.put("total_count",ipage.getTotal());
        map.put("items",records);
        return map;
    }
}
